#!/usr/bin/env python

from mxit import handles
from mxit import encryption
from mxit import errors
from blend import constants
import gtk
import gobject
import os
import gettext

gettext.install('blendIT','locale');

class listener:

   def __init__(self,blend):
      self.blend = blend;

   def status_changed(self,status,reason):
      convs = self.blend.gui.chatWindow.convs.conv.values();
      
      if status == handles.Status.DISCONNECTED:
         message = _("You are offline");
         self.blend.gui.chatWindow.systemMessage(message,convs,False);   
      elif status == handles.Status.ACTIVE:
         message = _("You are online");
         self.blend.gui.chatWindow.systemMessage(message,convs,False);
         

   # Splash images are handled by chatWindow
   # since it's displayed in the chat window...
   def splash_image(self,filename,data):
      tempFileName = os.path.join(self.blend.temp,filename);
      tempFile = open(tempFileName,'wb');
      tempFile.write(data);
      tempFile.close();

      # This isn't a real buddy... Don't treat it like one and
      # send it messages...
      buddy = handles.Buddy('splash@__Blendit','Splash',
                            tempFileName,handles.BuddyType.SPLASH);
      cW = self.blend.gui.chatWindow;
      if cW.convs.getByJID('splash@__Blendit') is not None:
         # delete the splash
         cW.destroyChat(jid='splash@__Blendit');
      
      cW.createNewChat(buddy,True,cW.drawSplashPage);


   # If a buddy in our contact list joins the MultiMx
   def room_buddies_joined(self,room,buddies):
      room = self.blend.gui.chatWindow.convs.getByJID(room.jid);
      if room is None:
         return; # Err0r
      for buddy in buddies:
         if str(buddy.name) != str(self.blend.currentAccount.name):
            room.mxtab.addBuddy(buddy);

   def room_buddies_left(self,room,buddies):
      room = self.blend.gui.chatWindow.convs.getByJID(room.jid);
      if room is None:
         return; # Err0r
      for buddy in buddies:
         room.mxtab.removeBuddy(buddy);

   def room_message_received(self,room,message):
      #print message.buddy, message.message, room;
      room = self.blend.gui.chatWindow.convs.getByJID(room.jid);
      room.mxtab.sendMessage(message.buddy,message);

   def buddy_updated(self,buddy,presence=None,mood=None,name=None,group=None,old_presence=None):     
      if mood != None:
         mood = constants.C.moods[mood];
         self.blend.gui.chatWindow.updateBuddyMood(buddy);
      if presence is not None or presence is handles.Presence.PENDING:
         presence = constants.C.presences[presence];
         self.blend.gui.chatWindow.updateBuddyPresence(buddy);
      if name is not None:
         self.blend.gui.chatWindow.updateBuddyName(buddy);

   def buddy_removed(self,buddy):
      conv = self.blend.gui.chatWindow.convs.getByJID(buddy.jid);
      if conv is None:
         return;
      else:
         # Ah.. We must make the buddy offline
         self.buddy_updated(buddy,handles.Presence.OFFLINE,handles.Mood.NONE);

         # System message that this buddy has been removed
         m = _("%s has been removed from your contact list. ") % str(buddy.name);
         m += _("You can no longer send messages to them.")
         self.blend.gui.systemMessage(m,[conv],False);
         
         # Finally, we have to get rid of the signals on the entry widget
         # so they can't send a message to a removed buddy.
         conv.convEntry.disconnect('mykeypress');

   def file_pending(self,file,buddy):
      self.blend.gui.chatWindow.updateConversationFilePending(buddy.jid,file);

   # We will have to display: <save to location> <open temp>
   def file_received(self,file,data):
      buddy = self.blend.conn.roster._files[file.id][1];
      try:
         f = os.path.join(self.blend.temp,file.name);
         tempFile = open(f,'wb');
         tempFile.write(data);
         tempFile.close();
      
         # We have to get the buddy who sent us the file from the file id.
         self.blend.gui.chatWindow.systemMessage(_("Downloaded %s") % str(file.name),spawn=True,jids=[buddy.jid]);
      
         # Now spawn the file save dialog
         gobject.timeout_add(150,self.blend.gui.saveDialog,file);
      except IOError:
         self.blend.gui.chatWindow.systemMessage(_("Failed to Download") % str(file.name),spawn=True,jids=[buddy.jid]);

   # Uh, oh.
   def message_error(self,message,response):
      buddy = message.buddy;
      conv = self.blend.gui.chatWindow.convs.getByJID(buddy.jid);
      if conv == None:
         # Create a new conversation
         n = self.blend.gui.chatWindow.createNewChat(buddy);
         conv = self.blend.gui.chatWindow.convs.getByPageNumber(n);

      self.blend.gui.chatWindow.errorMessage(str(response),spawn=True,convs=[conv]);

   def message_received(self,message):

      buddy = message.buddy;
      self.blend.gui.chatWindow.updateBuddyMessage(buddy,True);
      conv = self.blend.gui.chatWindow.convs.getByJID(buddy.jid);
      if conv == None:
         # Create a new conversation
         n = self.blend.gui.chatWindow.createNewChat(buddy);
         conv = self.blend.gui.chatWindow.convs.getByPageNumber(n);

      if handles.MessageFlags.ENCRYPTED in message.flags:
         message.flags.remove(handles.MessageFlags.ENCRYPTED);
         # Now we have to handle the encrypted message:
         if conv.receiveEncryptKey is not None:
            # We know the encryption key :D
            try:
               msg = encryption.decrypt_message(message.message,key);
               message.message = msg;
               self.blend.gui.chatWindow.parseMessage(message,conv);
            except errors.MxitException:
               # Ah. I guess we didn't know the key then...
               id = conv.storeMessage(message);
               n = str(conv.jid);

               m = _('%s has sent an encrypted message.') % str(buddy.name);
               m += ('Click to </span><span>');
               m += ('<a href="blendit://decrypt:%s:%s">Decrypt</a>') % (n,id);
               self.blend.gui.chatWindow.systemMessage(m,[conv],True);
         else:
            # We have no idea what the key is :(
            id = conv.storeMessage(message);
            n = str(conv.jid);

            m = _('%s has sent an encrypted message.') % str(buddy.name);
            m += ('Click to </span><span>');
            m += ('<a href="blendit://decrypt:%s:%s">Decrypt</a>') % (n,id);
            self.blend.gui.chatWindow.systemMessage(m,[conv],True);
      else:
         # It's a normal message! Yay
         #if message.type == handles.MessageType.COMMAND:
            # We have to parse the command stuff first.
            #p = self.blend.gui.chatWindow.parser;
            #m = p.mxitServiceParser(message.message);
            #message.message = "<br/>" + m.replace("\n","<br/>");

         self.blend.gui.chatWindow.parseMessage(message,conv);